import {queryOrderList} from "@src/api/booking";
import dayjs from "dayjs";
import router from "@src/router";

Component({
  behaviors: [router.routerBehavior],
  options: {
    addGlobalClass: true
  },
  data: {
    loading: false,
    hasNextPage: false,
    pageNum: 1,
    pageSize: 10,
    dayList:[]
  },
  lifetimes: {
    ready: function () {
      this.fetchData();
    }
  },
  methods: {
    fetchData() {
      let data = {orderType: 6, pageNum: this.data.pageNum, pageSize: this.data.pageSize}
      this.setData({loading: true})
      queryOrderList(data).then(res => {
        wx.stopPullDownRefresh();
        this.setData({loading: false})
        if (res.code === 0) {
          this.parseList(res.data.list)
          this.setData({hasNextPage: res.data.hasNextPage})
        }
      }).catch(() => {
        this.setData({loading: false})
      })
    },
    parseList(newList) {
      if (!newList || newList.length === 0) {
        return;
      }
      let dayMap = {}
      let lastDay = null;
      let dayList = this.data.dayList;
      if (dayList.length > 0) {
        lastDay = dayList[dayList.length - 1].day;
      }
      for (let order of newList) {
        let day = dayjs(order.createTime).format("YYYY-MM-DD");
        if (dayMap[day] === undefined) {
          dayMap[day] = [];
        }
        dayMap[day].push(order);
      }
      for (let day in dayMap) {
        if (lastDay !== null && day === lastDay) {
          dayList[dayList.length - 1].list.push(...dayMap[day])
        } else {
          dayList.push({day: day, list: dayMap[day]})
        }
      }
      this.setData({dayList: dayList})
    },
    onReachBottom() {
      if (this.data.hasNextPage) {
        this.setData({pageNum: this.data.pageNum + 1});
        this.fetchData();
      }
    },
    onPullDownRefresh() {
      wx.stopPullDownRefresh();
      this.setData({pageNum: 1, pageSize: 10, hasNextPage: false, dayList: []});
      this.fetchData();
    }
  }
});
